package gzhaoku.com.common.util;

import android.os.Environment;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import java.io.File;

import gzhaoku.com.common.Logger;
import gzhaoku.com.machinemain.BuildConfig;

/**
 * 设置
 *
 */
public class Setting {

    static final Logger log = Logger.getLog(Setting.class);

    static final String fileName = "machine-setting-"+ BuildConfig.APP_ID+".json";

    static File getSettingFile(){
        File dir = Environment.getExternalStorageDirectory();
        if(!dir.exists()){
            dir.mkdirs();
        }
        File settingFile = new File(dir, fileName);

        return settingFile;
    }

    static JSONObject getSetting(){
        File settingFile = getSettingFile();
        JSONObject settingData;
        if(settingFile.exists()){
            log.i("setting file: %s", settingFile.getAbsolutePath());
            String json = IOUtils.readFile(settingFile.getAbsolutePath());
            try{
                settingData = JSON.parseObject(json);
                if(settingData == null){
                    settingData = new JSONObject();
                }
            }catch (Exception e){
                log.e(e);
                settingData = new JSONObject();
            }

        }else{
            settingData = new JSONObject();
        }
        return settingData;
    }

    /**
     * 保存设置
     * @param key
     * @param value
     */
    public static synchronized void save(String key, String value){
        JSONObject settingData = getSetting();
        settingData.put(key, value);
        IOUtils.writeFile(getSettingFile().getAbsolutePath(), settingData.toJSONString());
    }

    /**
     * 读取设置
     * @param key
     * @return
     */
    public static synchronized String get(String key){
        JSONObject settingData = getSetting();
        if(settingData.containsKey(key)){
            return settingData.getString(key);
        }else{
            return null;
        }
    }


}
